<template>
  <el-row>
    <el-button type="primary" @click="showAddUserView">添加</el-button>
  </el-row>

  <el-row>
    <el-table ref="userDataTable" @selection-change="handleSelectChange" v-loading.lock="loading"  element-loading-text="数据拼命加载中..." element-loading-background="rgba(122, 122, 122, 0.8)" :data="userList" border style="width: 100%" stripe>
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="编号" width="120" />
      <el-table-column prop="name" label="姓名"  />
      <el-table-column prop="age" label="年龄"  />
      <el-table-column prop="position" label="身份"  />
      <el-table-column prop="addTime" :formatter="localDateFormat" label="添加时间"  />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" @click="showEditUserView(scope.$index, scope.row)">修改</el-button>
          <el-button size="small" type="primary" @click="toUserInfoDetails(scope.$index, scope.row)">详情</el-button>
          <el-button size="small" type="danger" @click="deleteUserInfo(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-row>

  <el-row>
    <el-button type="danger" @click="deleteBatch">批量删除</el-button>
  </el-row>


  <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="30%">
    <el-form
        ref="addUserFormRef"
        :rules="addUserFormRules"
        label-width="80px"
        :model="addUserInfo">
      <el-form-item label="姓名" prop="name">
        <el-input v-model.trim="addUserInfo.name"/>
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <el-input v-model="addUserInfo.age" />
      </el-form-item>
      <el-form-item label="身份" prop="position">
        <el-input v-model.trim="addUserInfo.position" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="resetAddUserForm(addUserFormRef)">取消</el-button>
        <el-button type="primary" @click="onAddOrUpdateUserInfo(addUserFormRef)">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {getCurrentInstance, onMounted, reactive, ref, toRefs} from "vue";
import {ElMessage, ElMessageBox, ElTable, FormInstance} from "element-plus";
import router from "@/router/router";
import loginUser from "../../../mock/loginUser";
import {User} from "@/types/User";

//获取全局发送请求的对象
const http = getCurrentInstance()?.appContext.config.globalProperties.$http
const dateFormat = getCurrentInstance()?.appContext.config.globalProperties.$dateFormat

// -----------响应式数据部分开始----------
const state = reactive({
  dialogTitle: '添加用户信息',
  userList: [],
  addUserInfo: {
    id: '',
    name: '',
    age: '',
    position: '',
    addTime: new Date()
  }
})

const { userList, addUserInfo, dialogTitle } = toRefs(state)

const loading = ref(true)
const dialogVisible = ref(false)
const addUserFormRef = ref<FormInstance>()
const userDataTable = ref<InstanceType<typeof ElTable>>()
const delBatchIds = ref<string>('')


const checkAge = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('年龄必须输入'))
  }
  if (!Number.parseInt(value)) {
    callback(new Error('请输入合法的数字'))
  } else {
    if (value < 0 || value > 150) {
      callback(new Error('年龄在1-150之间'))
    } else {
      callback()
    }
  }
}


// 添加用户校验规则
const addUserFormRules = reactive({
  name:[
    { required: true, message: '用户名必须输入', trigger: 'blur' },
    { min: 2, max: 15, message: '用户名长度在2-15之间', trigger: 'blur' },
  ],
  age:[
    { required: true, message: '年龄必须输入', trigger: 'blur' },
    { validator: checkAge, trigger: 'blur' },
  ],
  position: [
    { required: true, message: '身份必须输入', trigger: 'blur' },

  ]
})
// -----------响应式数据部分结束----------



// -----------方法部分开始----------
// 获取用户列表数据
const getUserList = async () => {
  const { data: res } = await http.get('/users')
  if (res.code !== 200) return ElMessage.error('获取数据失败！')
  userList.value = res.data
  loading.value = false
}

// 删除用户数据
const deleteUserInfo = (rowIndex:number, row:any) => {
  ElMessageBox.confirm(
      `确定要删除第[ ${rowIndex + 1} ]条数据吗?`,
      '提示信息',
      {confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning',}
  ).then(async () => {
    // axios delete bug 要添加data 后台才可以获取到数据
    const {data: res} = await http.delete('/users', {data: {id: row.id}})
    if (res.code !== 200) return ElMessage.error({ showClose: true, message: res.mes})
    ElMessage.success({showClose: true, message: res.mes})
    getUserList()
  }).catch(() => {
        ElMessage({
          showClose: true,
          type: 'info',
          message: '取消删除',
        })
      })
}

// 修改用户数据
const showEditUserView = (rowIndex:number, row:any) => {
  // 将用户点击的数据复制一份为要修改的数据
  addUserInfo.value.id = row.id
  addUserInfo.value.name = row.name
  addUserInfo.value.age = row.age
  addUserInfo.value.position = row.position
  addUserInfo.value.addTime = row.addTime
  dialogTitle.value ='修改用户信息'
  dialogVisible.value = true
}

// 显示添加用户信息
const showAddUserView = () => {
  dialogTitle.value = '添加用户信息'
  // 显示是清空修改时的信息
  state.addUserInfo = {
    id: '',
    name: '',
    age: '',
    position: '',
    addTime: new Date()
  }
  dialogVisible.value = true
}

// 跳转用户详情
const toUserInfoDetails = (rowIndex:number, row:any) => {
  router.push({
    path: '/user/userDetails',
    query: {
      id: row.id,
      name: row.name,
      age: row.age,
      position: row.position,
      addTime: row.addTime
    }
  })
}

// 处理表格选择事件，用来获取选中的数据的id
const handleSelectChange = (rows:User[]) => {
  if (rows){
    delBatchIds.value = rows.map(item => item.id).join()
  }
}

const deleteBatch = () => {
  const ids = delBatchIds.value.split(',')
  ElMessageBox.confirm(
      `确定要删除第选择的数据吗?`,
      '提示信息',
      {confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning',}
  ).then(async () => {
    // axios delete bug 要添加data 后台才可以获取到数据
    const {data: res} = await http.delete('/users', {data: {ids: ids}})
    if (res.code !== 200) return ElMessage.error({ showClose: true, message: res.mes})
    ElMessage.success({showClose: true, message: res.mes})
    getUserList()
  }).catch(() => {
    ElMessage({
      showClose: true,
      type: 'info',
      message: '取消删除',
    })
  })
}

// 添加或修改用户
const onAddOrUpdateUserInfo = async (formEl: FormInstance | undefined) => {
  // 不存在id 为添加
  if (!formEl) return
  formEl.validate(async (valid) => {
    // 验证通过判断 是否有id ,有id为修改没有则为添加
    if (valid) {
      if (state.addUserInfo.id){
        // 存在id 为修改
        const {data:res} = await http.put('/users', state.addUserInfo)
        if (res.code !== 200) return ElMessage.error({showClose: true, message: res.mes})
        ElMessage.success({showClose: true, message: res.mes})
        // 更新数据
        getUserList()
        // 重置表单关闭对话框
        resetAddUserForm(addUserFormRef.value)
      } else {
        // 发送添加用户请求
        // 设置时间为用户的id
        state.addUserInfo.id = new Date().toDateString()
        const {data: res} = await http.post('/users', state.addUserInfo)
        if (res.code !== 200) return ElMessage.error({showClose: true, message: res.mes})
        ElMessage.success({showClose: true, message: res.mes})
        // 刷新数据
        getUserList()
        // 重置表单
        resetAddUserForm(addUserFormRef.value)
      }
    } else {
      ElMessage.error({showClose: true, message: '请输入合法信息'})
      return false
    }
  })
}

// 添加用户表单的重置
const resetAddUserForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  dialogVisible.value = false
  formEl.resetFields()
}

// 表格日期格式化
const localDateFormat = (row:any, column:any) => {
  const date = row[column.property]
  return dateFormat(date)
}
// -----------方法部分结束----------


// 组件挂载后请求数据
onMounted(() => {
  getUserList()
})
</script>

<style lang="less" scoped>
.el-row {
  margin-bottom: 15px;
}
.el-row:last-child {
  margin-bottom: 0;
}
</style>
